package com.example.springboot.redis.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    private static final Logger log = LoggerFactory.getLogger(RabbitMQConfig.class);
    /**
     * 配置JSON序列化，替代默认JDK序列化
     * @return
     */
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 消费者重试与死信队列
     * @return
     */
    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", "order.dlx.exchange");  // 死信交换机
        args.put("x-dead-letter-routing-key", "order.dead");       // 死信路由键
        return new Queue("order.queue", true, false, false, args);
    }

    /**
     * RabbitTemplate
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());

        // 消息发送到 Exchange 确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("消息到达 Exchange: {}", correlationData.getId());
            } else {
                log.error("消息未到达 Exchange: {}, 原因: {}", correlationData.getId(), cause);
            }
        });

        // 消息从 Exchange 路由到 Queue 失败回调
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("消息路由到队列失败: {}", returned.getMessage());
        });

        return rabbitTemplate;
    }

    /**
     * 消费者并发配置
     * @param connectionFactory
     * @param messageConverter
     * @return
     */
    @Bean
    public SimpleRabbitListenerContainerFactory customContainerFactory(
            ConnectionFactory connectionFactory,
            MessageConverter messageConverter) {

        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(messageConverter);
        factory.setConcurrentConsumers(5);   // 最小并发消费者数
        factory.setMaxConcurrentConsumers(10); // 最大并发消费者数
        factory.setPrefetchCount(50);        // 每个消费者预取消息数
        return factory;
    }
}


